import { getToken, setToken as _setToken, removeToken } from "@/utils";
import { createSlice } from "@reduxjs/toolkit";
import { getToken as loginApi } from "@/apis/user";

const tokenStore = createSlice({
  name: "token",
  initialState: {
    token: getToken() || "",
  },
  reducers: {
    setToken(state, action) {
      state.token = action.payload;
      _setToken(action.payload); // 存储到本地存储中
    },
    clearToken(state) {
      state.token = "";
      removeToken(); // 从本地存储中移除
    },
  },
});

const { setToken, clearToken } = tokenStore.actions;

const reducer = tokenStore.reducer;

interface LoginData {
  username: string;
  password: string;
}

// 异步方法获取登录信息
const fetchLogin = (data: LoginData) => {
  return async (dispatch: any) => {
    //   发送异步请求获取登录信息
    const res = await loginApi(data);
    //   提交同步action存入token
    dispatch(setToken(res.token));
  };
};

export { setToken, clearToken, fetchLogin };

export default reducer;
